package com.example.yimai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.yimai.entity.Address;
import com.example.yimai.mapper.AddressMapper;
import com.example.yimai.service.AddressService;
import com.example.yimai.utils.JWTUtil;
import com.example.yimai.utils.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {

    @Autowired
    private JWTUtil jwtUtil;

    @Override
    public String addAddress(String token, Map<String, Object> params) {
        try{
            // 去除Bearer前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            Address address = parseParams(params);
            address.setUserId(Integer.parseInt(jwtUtil.getId(token)));
            address.setCreateTime(new Date());
            save(address);
            return "success";
        }catch (Exception e){
            throw new RuntimeException("添加地址失败"+e.getMessage());
        }
    }

    @Override
    public String deleteAddress(Integer id) {
        try {
            removeById(id);
            return "success";
        }catch (Exception e){
            throw new RuntimeException("删除地址失败"+e.getMessage());
        }
    }

    @Override
    public String updateAddress(Map<String, Object> params) {
        try {
            Address address = parseParams(params);
            updateById(address);
            return "success";
        }catch (Exception e){
            throw new RuntimeException("更新地址失败"+e.getMessage());
        }
    }

    @Override
    public Address getAddress(Integer id) {
        try {
            return getById(id);
        }catch (Exception e){
            throw new RuntimeException("获取地址失败"+e.getMessage());
        }
    }

    @Override
    public List<Address> getAllAddress(String token) {
        try{
            // 去除Bearer前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userId",jwtUtil.getId(token));
            return list(queryWrapper);
        }catch (Exception e){
            throw new RuntimeException("获取地址失败"+e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String setDefault(String userId, String addressId) {
        try {
            // 先检查要设置为默认的地址是否属于该用户
            QueryWrapper<Address> checkWrapper = new QueryWrapper<>();
            checkWrapper.eq("id", addressId);
            checkWrapper.eq("userId", userId);
            Address addressToSet = getOne(checkWrapper);
            
            if (addressToSet == null) {
                throw new RuntimeException("地址不存在或不属于该用户");
            }
            
            // 将该用户的所有地址设置为非默认
            UpdateWrapper<Address> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("userId",userId);
            updateWrapper.set("isDefault",0);
            update(updateWrapper);
            
            // 将指定地址设置为默认
            updateWrapper.clear();
            updateWrapper.eq("id",addressId);
            updateWrapper.set("isDefault",1);
            update(updateWrapper);
            
            return "success";
        }catch (Exception e){
            throw new RuntimeException("设置默认地址失败"+e.getMessage());
        }
    }

    @Override
    public Address getDefaultAddress(String userId) {
        try {
            QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userId",userId);
            queryWrapper.eq("isDefault",1);
            return getOne(queryWrapper);
        }catch (Exception e){
            throw new RuntimeException("获取默认地址失败"+e.getMessage());
        }
    }

    public Address parseParams(Map<String, Object> params){
        Address address = new Address();

        address.setId(ParamUtil.parseParams(params,"id"));
        address.setAddress(ParamUtil.parseParams(params,"address"));
        address.setRemark(ParamUtil.parseParams(params,"remark"));
        address.setReceiveName(ParamUtil.parseParams(params,"receiveName"));
        address.setMobile(ParamUtil.parseParams(params,"mobile"));

        return address;
    }

}
